<template>
  <div>
    <el-upload
      action=""
      :limit="5"
      :file-list="fileLists"
      :on-exceed="uploadOverrun"
      :before-upload="
              (file) => handleBeforeUpload(file)
            "
      class="avatar-uploader"
      :on-remove="handleRemove"
      accept=".jpg,.jpeg,.png,.gif"
      list-type="picture-card"
    >
      <i class="el-icon-plus"/>
    </el-upload>
    <image-cropper
      v-model="showCrop"
      :imgSrc="imgSrc"
      :cropWidth="cropWidth"
      :cropHeight="cropHeight"
      @uploadSuccess="uploadSuccess"
    ></image-cropper>
  </div>
</template>

<script>
import { getToken } from '@/utils/auth'
import { uploadPath } from '@/api/business/storage'
import ImageCropper from "@/components/ImageCropper"

export default {
  name: "ShopUpLoads",
  components: {
    ImageCropper
  },
  props: {
    fileList: {
      type: [Array],
      default: () => {
      }
    },
    cropWidth: {
      type: [Number],
      default: () => 200
    },
    cropHeight: {
      type: [Number],
      default: () => 100
    }
  },
  data() {
    return {
      uploadPath,
      showCrop: false, // 展示裁切框
      imgSrc: "",
      fileLists: this.fileList
    }
  },
  watch: {
    fileList(val) {
      console.log(val)
      this.fileLists = val
    }
  },
  computed: {
    headers() {
      return {
        "X-Dts-Merchant-Token": getToken(),
      };
    }
  },
  methods: {
    uploadOverrun: function() {
      this.$message({
        type: "error",
        message: "上传文件个数超出限制!最多上传5张图片!"
      })
    },
    handleRemove: function(file, fileList) {
      var url = file.url
      for (var i = 0; i < this.fileLists.length; i++) {
        if (this.fileLists[i].url === url) {
          this.fileLists.splice(i, 1)
        }
      }
      // 返回给父组件
      this.$emit('on-upload-success', {
        fileList: this.fileLists
      })
    },
    handleBeforeUpload(file) {
      this.imgSrc = URL.createObjectURL(file) // 创建图片地址用于显示和裁切
      this.showCrop = true // 打开裁切对话框
      return false // 不自动上传，由用户手动触发上传
    },
    generateUID(){
      return  `${Date.now()}_${Math.random().toString(36).substr(2)}`
    },
    uploadSuccess(file) {
      var data = { uid: this.generateUID(), url: file, status: 'done' }
      this.fileLists.push(data)
      console.log(this.fileLists)
      // 返回给父组件
      this.$emit('on-upload-success', {
        fileList: this.fileLists
      })
    }
  }
}
</script>

<style scoped>

</style>
